﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DataAccessLayer;
using System.IO;

public partial class webadmin_pages_trangchu_cauhinh : System.Web.UI.Page
{
    public Common comm = new Common();
    DataRow catdtr;
    public DataTable dtt, dtt_top, dtt_right, dtt_center, dtt_centerdouble, dtt_footer, dtt_menu;
    public string act = "", acts = "";
    public string id = "", idb = "";
    string[] temp;
    public static string[] aCenter, aCenterDouble, aRight, aTop, aBottom, aSub;
    string sTemp;
    public string messageError;

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack) loadcombo();
            if (!string.IsNullOrEmpty(Request.QueryString["acts"])) acts = comm.TextFormat(Request.QueryString["acts"]).Trim();
            if (!string.IsNullOrEmpty(Request.QueryString["idb"])) idb = comm.TextFormat(Request.QueryString["idb"]).Trim();
            sTemp = "select * from CreatePages_page where notes is NOT NULL";
            catdtr = comm.getDataTable(sTemp).Rows[0];
            
            if (!IsPostBack)
            {
                txtTieuDe.Text = string.IsNullOrEmpty(catdtr["title"].ToString()) ? "" : catdtr["title"].ToString();
                txtNoiDung.Html = string.IsNullOrEmpty(catdtr["footer_text"].ToString()) ? "" : catdtr["footer_text"].ToString();
                LoadDanhMucGoc("");//Load cho phan banner
            }
            //Doc tat ca cac block hien co cua page nay va dua vao cac mang tuong ung
            string sql_select = "SELECT B.*,C.* FROM dbo.CreatePages_page_block AS B" +
                " INNER JOIN dbo.CreatePages_block AS C ON B.id_block = C.id_block";
            string sql_order = " ORDER BY B.order_block";
            //Panel CENTER
            string sql_where = " WHERE id_page=" + catdtr["id_page"].ToString() + " and C.position='center' AND B.notes IS NULL";
            dtt_center = comm.getDataTable(sql_select + sql_where + sql_order);
            //Panel CENTER DOUBLE
            sql_where = " WHERE id_page=" + catdtr["id_page"].ToString() + " and C.position='center' AND B.notes IS NOT NULL";
            dtt_centerdouble = comm.getDataTable(sql_select + sql_where + sql_order);
            //Panel RIGHT
            sql_where = " WHERE id_page=" + catdtr["id_page"].ToString() + " and C.position='right'";
            dtt_right = comm.getDataTable(sql_select + sql_where + sql_order);
           
            //PANEL RIGHT                                
            if (!IsPostBack)
            {
                for (int i = 0; i < dtt_right.Rows.Count; i++)
                {
                    if (!(String.IsNullOrEmpty(dtt_right.Rows[i]["path"].ToString())))
                    {
                        switch (dtt_right.Rows[i]["id_block"].ToString())
                        {
                            case "7": chkBangCungCau.Checked = true; break;
                            case "8": chkThongKe.Checked = true; break;//case "17": chkTopBanner.Checked = true; break;
                            case "9": chkHoTroTrucTuyen.Checked = true; break;
                            case "10": chkLienKet.Checked = true; break;
                        }
                    }
                }
            }
            //PANEL CENTER
            if ((Session["aCenter"] != null) && acts == "center")//Nếu có tồn tại mảng right rồi
            {
                temp = (string[])Session["aCenter"];
                if (acts == "center" && idb != "") //nếu lựa chọn bỏ một phần trong mảng right
                {
                    aCenter = new string[temp.Length - 1];
                    for (int i = 0; i < temp.Length; i++)
                    {
                        if (i >= int.Parse(idb))
                        {
                            if (i != temp.Length - 1)
                                aCenter[i] = temp[i + 1];
                        }
                        else
                            aCenter[i] = temp[i];
                    }
                }
                else aCenter = temp;
                Session.Remove("aCenter");
                Session.Add("aCenter", aCenter);
            }
            else if (Session["aCenter"] == null)
            {
				if(!IsPostBack){
					aCenter = new string[dtt_center.Rows.Count];
					for (int i = 0; i < dtt_center.Rows.Count; i++)
					{
						aCenter[i] = dtt_center.Rows[i]["id_block"].ToString() + "-" + dtt_center.Rows[i]["name_block"].ToString() + "-" +
						dtt_center.Rows[i]["order_block"].ToString();
					}
					Session.Remove("aCenter");
					Session.Add("aCenter", aCenter);
				}
            }
            //Thiết lập các đối tượng theo ..


            //PANEL CENTER DOUBLE
            //if(btnAddCenter.a)
            if ((Session["aCenterDouble"] != null) && acts == "centerdouble")//Nếu có tồn tại mảng right rồi
            {
                temp = (string[])Session["aCenterDouble"];//"tên block trái"-"tên block phải"-"thứ tự"
                if (acts == "centerdouble" && idb != "") //nếu lựa chọn bỏ một phần trong mảng right
                {
                    aCenterDouble = new string[temp.Length - 1];
                    for (int i = 0; i < temp.Length; i++)
                    {
                        if (i >= int.Parse(idb))
                        {
                            if (i != temp.Length - 1)
                                aCenterDouble[i] = temp[i + 1];
                        }
                        else
                            aCenterDouble[i] = temp[i];
                    }
                }
                else aCenterDouble = temp;
                Session.Remove("aCenterDouble");
                Session.Add("aCenterDouble", aCenterDouble);
            }
            else if (Session["aCenterDouble"] == null)
            {
				if(!IsPostBack){
					aCenterDouble = new string[dtt_centerdouble.Rows.Count];
					for (int i = 0; i < dtt_centerdouble.Rows.Count; i++)
					{
						string[] s = dtt_centerdouble.Rows[i]["notes"].ToString().Split('-');//B.notes=1-12
						String leftBlock = comm.execScalar("select name_block from CreatePages_block where id_block=" + s[0].ToString());
						String rightBlock = comm.execScalar("select name_block from CreatePages_block where id_block=" + s[1].ToString());
						aCenterDouble[i] = leftBlock + "-" + rightBlock + "-" +
						dtt_centerdouble.Rows[i]["order_block"].ToString() + "-" + dtt_centerdouble.Rows[i]["notes"].ToString();
					}
					Session.Remove("aCenterDouble");
					Session.Add("aCenterDouble", aCenterDouble);
				}
            }
            //Thiết lập các đối tượng theo ..
            if (acts != "") Response.Redirect("trangchu_cauhinh.aspx");
        }
        catch (Exception ex)
        {
            messageError = "Lỗi - " + ex.Message + "-" + ex.ToString();
        }
    }
	
    private void loadcombo()
    {
        ListItem li;
        string sql_select = "select id_block,name_block from CreatePages_block where position='center' and notes like '%tt%'";
        dtt = comm.getDataTable(sql_select);
        cboCenter.Items.Clear(); cboCenterDoubleLeft.Items.Clear(); cboCenterDoubleRight.Items.Clear();
        for (int i = 0; i < dtt.Rows.Count; i++)
        {
            li = new ListItem(dtt.Rows[i][1].ToString(), dtt.Rows[i][0].ToString());
            cboCenter.Items.Add(li); cboCenterDoubleLeft.Items.Add(li); cboCenterDoubleRight.Items.Add(li);
        }
    }
    protected void LoadDanhMucGoc(string tenfile)
    {
        string mess = Page.MapPath("");
        mess = mess.Remove(mess.LastIndexOf('\\'));
        mess = mess.Remove(mess.LastIndexOf('\\'));
        cboListBanner.Items.Clear();
        ListItem li;
        string[] duongdan;
        DataTable catdtt1;
        //Đọc danh sách file banner hiện có

        string[] filePaths = Directory.GetFiles(@"" + mess + "\\Uploads\\Banner\\");
        for (int i = 0; i < filePaths.Length; i++)
        {
            mess += "<br/>" + filePaths[i].ToString();
            duongdan = filePaths[i].ToString().Split('\\');
            li = new ListItem(duongdan[duongdan.Length - 1]);
            cboListBanner.Items.Add(li);
        }
        if (tenfile == "") //nếu rỗng thì ta lấy từ cơ sở dữ liệu
        {
            catdtt1 = comm.getDataTable("Select * from CreatePages_page where id_page=" + catdtr["id_page"].ToString());
            if (!string.IsNullOrEmpty(catdtt1.Rows[0]["banner_path"].ToString()))
            {
                string[] aa = catdtt1.Rows[0]["banner_path"].ToString().Split('/');
                cboListBanner.Items.FindByText(aa[aa.Length - 1].ToString()).Selected = true;
            }
        }
        else
        {
            cboListBanner.Items.FindByText(tenfile).Selected = true;
        }
    }
    public string SaveFile(FileUpload file, string iloaifile)
    {
        try
        {
            if ((file.PostedFile != null) && (file.PostedFile.InputStream.Length > 0))
            {
                String fileExtension =
                    System.IO.Path.GetExtension(file.FileName).ToLower();
                string path = "../../Uploads/Banner/";

                try
                {
                    file.PostedFile.SaveAs(Server.MapPath(path) + file.FileName);
                    return (file.FileName);
                }
                catch (Exception ex)
                {
                    messageError = "Không thể upload file." + ex.Message;
                    return "";
                }
            }
            else
                //mess = "Chưa chọn file để upload hoặc file này không tồn tại!";
                return "";
        }
        catch (Exception e)
        {
            messageError = e.Message;
            return "";
        }
    }
    protected void btnOk_Click(object sender, EventArgs e)
    {
        try
        {
            //Kiem tra va post hinh
            if (!string.IsNullOrEmpty(txtHinhAnh.FileName))
            {
                LoadDanhMucGoc(SaveFile(txtHinhAnh, "1"));
            }
            comm.execNoneQuery("UPDATE dbo.HeThong_config SET banner_path=N'Uploads/Banner/" + cboListBanner.Text + "' where id=1").ToString();
            //Kiểm tra nếu là add hay edit
            string sql = "UPDATE dbo.CreatePages_page set " +
                "title=N'" + txtTieuDe.Text + "'," +
                "banner_path=N'../../Uploads/Banner/" + cboListBanner.Text + "'," +
                "footer_text=N'" + txtNoiDung.Html + "'" +
                " where id_page=" + catdtr["id_page"].ToString();
            comm.execNoneQuery(sql);
            sql = "delete from CreatePages_page_block where id_page=" + catdtr["id_page"].ToString();
            int id_page = comm.execNoneQuery(sql);
            addBlock(catdtr["id_page"].ToString());
            btnCancel_Click(null, null);
        }
        catch (Exception err)
        {
            messageError += err.ToString();
        }

    }
    private void addBlock(string id_page)
    {
        try
        {
            string sql = "";
            //Insert các thành phần khác vào bảng CreatePages_page_block
            if (chkBangCungCau.Checked)
            {
                sql = "INSERT dbo.CreatePages_page_block" +
                    "( id_page ,id_block)" +//notes
                    "VALUES  ( " +
                    id_page + ",7" + ")";
                comm.execNoneQuery(sql);
            }
            if (chkHoTroTrucTuyen.Checked)
            {
                sql = "INSERT dbo.CreatePages_page_block" +
                    "( id_page ,id_block)" +//notes
                    "VALUES  ( " +
                    id_page + ",9" + ")";
                comm.execNoneQuery(sql);
            }
            if (chkLienKet.Checked)
            {
                sql = "INSERT dbo.CreatePages_page_block" +
                    "( id_page ,id_block)" +//notes
                    "VALUES  ( " +
                    id_page + ",10" + ")";
                comm.execNoneQuery(sql);
            }
            if (chkThongKe.Checked)
            {
                sql = "INSERT dbo.CreatePages_page_block" +
                    "( id_page ,id_block)" +//notes
                    "VALUES  ( " +
                    id_page + ",8" + ")";
                comm.execNoneQuery(sql);
            }

            if (Session["aCenter"] != null)
            {
                aCenter = (string[])Session["aCenter"];
                for (int i = 0; i < aCenter.Length; i++)
                {
                    temp = aCenter[i].Split('-');
                    sql = "INSERT dbo.CreatePages_page_block" +
                    "( id_page ,id_block ,order_block)" +//notes
                    "VALUES  ( " +
                    id_page + "," + temp[0].ToString() + "," + temp[2].ToString() +
                    ")";
                    comm.execNoneQuery(sql);
                }
            }
            if (Session["aCenterDouble"] != null)
            {
                aCenterDouble = (string[])Session["aCenterDouble"];
                for (int i = 0; i < aCenterDouble.Length; i++)
                {
                    temp = aCenterDouble[i].Split('-');
                    sql = "INSERT dbo.CreatePages_page_block" +
                    "( id_page ,id_block ,order_block,notes)" +//notes
                    "VALUES  ( " +
                    id_page + "," + 17 + "," + temp[2].ToString() + ",'" + temp[3].ToString() + "-" + temp[4].ToString() + "'" +//2-3-4
                    ")";
                    comm.execNoneQuery(sql);
                }
            }
        }
        catch (Exception er)
        {
            messageError = er.Source.ToString() + "-" + er.ToString();
        }
    }
    protected void btnAddCenter_Click(object sender, EventArgs e)
    {
        if (Session["aCenter"] != null)
        {
            temp = (string[])Session["aCenter"];
            aCenter = new string[temp.Length + 1];
            for (int i = 0; i < temp.Length; i++)
                aCenter[i] = temp[i];
            aCenter[aCenter.Length - 1] = cboCenter.SelectedValue.ToString() + "-" + cboCenter.SelectedItem.Text.ToString() + "-" + txtOrderCenter.Text;
            Session.Remove("aCenter"); Session.Add("aCenter", aCenter);
        }
        else
        {
            aCenter = new string[1];
            aCenter[0] = cboCenter.SelectedValue.ToString() + "-" + cboCenter.SelectedItem.Text.ToString() + "-" + txtOrderCenter.Text;
            Session.Remove("aCenter"); Session.Add("aCenter", aCenter);
        }
    }
    protected void btnAddCenterDouble_Click(object sender, EventArgs e)
    {
        if (Session["aCenterDouble"] != null)
        {
            temp = (string[])Session["aCenterDouble"];
            aCenterDouble = new string[temp.Length + 1];
            for (int i = 0; i < temp.Length; i++)
                aCenterDouble[i] = temp[i];
            aCenterDouble[aCenterDouble.Length - 1] = cboCenterDoubleLeft.SelectedItem.Text.ToString() +
                "-" + cboCenterDoubleRight.SelectedItem.Text.ToString() + "-" + txtOrderCenterDouble.Text + "-" +
                cboCenterDoubleLeft.SelectedValue.ToString() + "-" + cboCenterDoubleRight.SelectedValue.ToString();
            Session.Remove("aCenterDouble"); Session.Add("aCenterDouble", aCenterDouble);

        }
        else
        {
            aCenterDouble = new string[1];
            aCenterDouble[0] = cboCenterDoubleLeft.SelectedItem.Text.ToString() +
                "-" + cboCenterDoubleRight.SelectedItem.Text.ToString() + "-" + txtOrderCenterDouble.Text + "-" +
                cboCenterDoubleLeft.SelectedValue.ToString() + "-" + cboCenterDoubleRight.SelectedValue.ToString();
            Session.Remove("aCenterDouble"); Session.Add("aCenterDouble", aCenterDouble);
        }
    }
   
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Session.Remove("aRight"); Session.Remove("aCenter");
        Session.Remove("aCenterDouble");
        Response.Redirect("trangchu_cauhinh.aspx");
    }
}

